import {constantRoutes, getWhiteList, router} from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {useUserStore} from "@/store";
import {usePermissionStore} from "@/store/modules/permission";
import {RouterName} from "@/utils/enum-type";

NProgress.configure({showSpinner: false}); // 进度条

// 白名单路由
const whiteList = getWhiteList(constantRoutes)
// 如果已经请求了角色,但是角色为空
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken = localStorage.getItem("accessToken");
    // debugger
    if (hasToken) {
        // if (to.path === "/login") {
        if (to.name === RouterName.Login) {
            // 如果已登录，跳转首页
            next({name:RouterName.Layout});
            NProgress.done();
        } else {
            const userStore = useUserStore();
            const hasRoles = userStore.roles && userStore.roles.length > 0;
            if (hasRoles) {
                // 未匹配到任何路由，跳转404
                if (to.matched.length === 0) {
                    from.name ? next({name: from.name}) : next({name:RouterName.NotFound});
                } else {
                    next();
                }
            } else {
                try {
                    const permissionStore = usePermissionStore()
                    const {roles} = await userStore.getInfo();
                    if (roles && roles.length > 0) {
                        const accessRoutes = await permissionStore.generateRoutes(roles);
                        accessRoutes.forEach((route) => {
                            router.addRoute(RouterName.Sys, route);
                        });
                        next({...to, replace: true});
                    } else {
                        // 这里做了更改,如果用户没有角色,程序会不停的查询角色,所以这里应该抛出错误
                        ElMessage.error('该用户没有角色,无法登陆!')
                        throw new Error('该用户没有角色!')
                    }
                } catch (error) {
                    // 这里是有token,但是无法联网查询到角色或者是该用户没有角色,这时只能访问白名单
                    if (to.name && whiteList.includes(to.name)) {
                        next();
                    } else {
                        next(`/login?redirect=${to.path}`);
                        NProgress.done();
                    }
                }
            }
        }
    } else {
        // 未登录可以访问白名单页面
        if (to.name && whiteList.includes(to.name) || to.path === '/login') {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
            NProgress.done();
        }
    }
});
// 暂时先用自己写的
// router.beforeEach((to, from, next) => {
//   const userUser = useUserStore()
//   const {accessToken} = userUser
//   if (!whiteList.includes(to.path) && !accessToken) {
// 	next({path: '/login'})
//   } else {
// 	next()
//   }
// })

router.afterEach(() => {
    NProgress.done();
});
